package com;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

public class MyFilter implements Filter {

    private String sourceAddress = "localhost";
    private String sourceContext = null;
    private String targetAddress = "127.0.0.1";
    private String targetPort = "80";
    private String targetContext = null;

    @Override
    public void destroy() {
        System.out.println("destroy");

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        response.setCharacterEncoding("UTF-8");

        StringBuffer url = request.getRequestURL();
        System.out.println("url:" + url);

        if (url != null && !url.toString().isEmpty()) {
            String urls[] = url.toString().split("//");
            if (urls[1] != null && !"".equals(urls[1])) {
                String ips[] = urls[1].split("/");
                if (ips[0] != null && !"".equals(ips[0])) {
                    String ip = ips[0];
                    String uri = request.getRequestURI();
                    System.out.println("sourceAddress:" + sourceAddress);
                    System.out.println("ip:" + ip);
                    System.out.println("uri:" + uri);
                    if (sourceAddress.equals(ip)) {
                        System.out.println("重定向");
                        HttpURLConnection http = null;
                        ServletInputStream inputOfBrowser = null;
                        OutputStream outToTarget = null;
                        InputStream inputStreamFromTarget = null;
                        try {
                            String fullTargetUtl = null;

                            if (targetContext == null || targetContext.trim().isEmpty() || targetContext.trim().equals("null")) {
                                fullTargetUtl = "http://" + targetAddress + ":" + targetPort + uri;
                            } else {
                                String contextPath = request.getContextPath();
                                System.out.println("contextPath:" + contextPath);
                                if (contextPath == null || contextPath.trim().isEmpty() || contextPath.trim().equals("/")) {
                                    fullTargetUtl = "http://" + targetAddress + ":" + targetPort + "/" + targetContext + uri;
                                } else {
                                    String pureUri = StringUtils.removeStart(uri, contextPath);
                                    System.out.println("pureUri:" + pureUri);
                                    fullTargetUtl = "http://" + targetAddress + ":" + targetPort + "/" + targetContext + pureUri;
                                    System.out.println("fullTargetUtl:" + fullTargetUtl);
                                }
                            }
                            if (fullTargetUtl.endsWith("/")) {
                                fullTargetUtl = StringUtils.removeEnd(fullTargetUtl, "/");
                            }
                            int port80Index = fullTargetUtl.indexOf(":80/");
                            if (port80Index > 0) {
                                fullTargetUtl = fullTargetUtl.substring(0,port80Index)+"/"+fullTargetUtl.substring(port80Index+4);
                            }
                            System.out.println("Full target url :" + fullTargetUtl);

                            //获取request流
                            inputOfBrowser = request.getInputStream();

                            //建立重定向服务连接
                            URL targetUrlObj = new URL(fullTargetUtl);
                            http = (HttpURLConnection) targetUrlObj.openConnection();
                            http.setDoOutput(true);
                            http.setDoInput(true);
                            http.setRequestMethod(request.getMethod());

                            //向重定向服务发送请求
                            outToTarget = http.getOutputStream();
                            System.out.println(inputOfBrowser.available());
                            byte[] buf = new byte[inputOfBrowser.available()];
                            int i = 0;
                            while ((i = inputOfBrowser.read(buf)) != -1) {
                                //把从浏览器端接受到的数据，原样写入目标方
                                outToTarget.write(buf);
                                System.out.println(new String(buf));
                            }
                            outToTarget.flush();
                            //向重定向服务发送请求 结束

                            //向客户端返回请求
                            //从http请求中，拿到目标方返回的数据
                            inputStreamFromTarget = http.getInputStream();
                            if (inputStreamFromTarget == null) {
                                System.out.println("inputStreamFromTarget==null");
                                return;
                             }

                            byte[] buf1 = new byte[inputStreamFromTarget.available()];
                            //向浏览器响应数据
                            OutputStream resp = response.getOutputStream();
                            String sb = null ;
                            while ((i = inputStreamFromTarget.read(buf1)) != -1) {
//                            	sb = new String(buf1,"GBK") ;
//                            	if (sb.indexOf("href=")!=-1) {
//                            		System.out.println(sb.indexOf("href"));
//                            		sb = sb.replaceAll("href=\"", "href=\"http://192.168.1.111:9116/dms/");
//                            		sb = sb.replaceAll("src=\"", "src=\"http://192.168.1.111:9116/dms/");
//                            		System.out.println(sb);
//                            		resp.write(sb.getBytes());
//                            	}
//                            	else {
//                            	}
                            	resp.write(buf1);
                            	
                                Thread.sleep(4);
                            }
                            resp.flush();
                            //向客户端返回请求 结束
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            System.out.println("请求未找到！");
                            InputStream is = http.getErrorStream();//通过getErrorStream了解错误的详情，因为错误详情也以XML格式返回，因此也可以用JDOM来获取。 
                            if (is == null) {
                                byte[] a = (ex.getClass().getName() + " | " ).getBytes();
                                byte[] b = ex.getMessage().getBytes("UTF-8");
                                ByteBuffer bb = ByteBuffer.allocate(a.length+b.length);
                                bb.put(a);
                                bb.put(b);
                                is = new ByteArrayInputStream(bb.array());
                            }
                            BufferedReader isr = new BufferedReader(new InputStreamReader(is));
                            String line;
                            Writer out = response.getWriter();
                            while ((line = isr.readLine()) != null) {
                                out.write(line);
                            }
                            out.flush();
                        } finally {
                            if (outToTarget != null) {
                                outToTarget.close();
                            }
                            if (inputOfBrowser != null) {
                                inputOfBrowser.close();
                            }
                            if (inputStreamFromTarget != null) {
                                inputStreamFromTarget.close();
                            }
                        }
                    } else {
                        System.out.println("url不在配置中" + uri);
                        request.getRequestDispatcher(uri).forward(request, response);

                    }
                } else {
                    System.out.println("ips为空");
                }
            }
        } else {
            //跳转到错误页面
            System.out.println("跳转到错误页面");
        }
        System.out.println("结束！！！");

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        sourceAddress = filterConfig.getInitParameter("sourceAddress");
        sourceContext = filterConfig.getInitParameter("sourceContext");
        targetAddress = filterConfig.getInitParameter("targetAddress");
        targetPort = filterConfig.getInitParameter("targetPort");
        targetContext = filterConfig.getInitParameter("targetContext");
    }

}
